package com.yun.zhong.fu.cloudgateway.defeination;

import org.springframework.cloud.gateway.handler.predicate.AbstractRoutePredicateFactory;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;

import java.time.LocalDateTime;
import java.time.LocalTime;
import java.time.format.DateTimeFormatter;
import java.time.format.FormatStyle;
import java.util.Arrays;
import java.util.List;
import java.util.function.Predicate;

/**
 * @Author RenPu
 * @Date 2021/1/5 11:37
 * @Version 1.0
 * @Description: 实现自定义路由规则编写
 **/
@Component
public class TimeBetweenRoutePredicateFactory extends AbstractRoutePredicateFactory<TimeBetweenConfig> {
    public TimeBetweenRoutePredicateFactory() {
        super(TimeBetweenConfig.class);
    }

    @Override
    public Predicate<ServerWebExchange> apply(TimeBetweenConfig config) {

        //取出配置文件设定好的起始时间，结束时间
        LocalTime start = config.getStart();
        LocalTime end = config.getEnd();
        return exchange->{
            //与当前时间进行比较，如果当前时间大于起始时间，同时又小于结束时间则可以访问
            LocalTime localTime = LocalTime.now();
            return localTime.isAfter(start) && localTime.isBefore(end);
        };
    }



    /**
     * 配置类与配置文件进行映射的处理
     * @return
     */
    @Override
    public List<String> shortcutFieldOrder() {
        return Arrays.asList("start","end");
    }


    /**
     * 打印gateway，底层时间的设置规格为什么类型
     * @param args
     */
    public static void main(String[] args) {
        DateTimeFormatter formatter = DateTimeFormatter.ofLocalizedTime(FormatStyle.SHORT);
        System.out.println(formatter.format(LocalTime.now()));

    }
}
